<template>
  <div class="table-wrapper">
    <el-table
      v-bind="$attrs"
      v-loading="tableLoading"
      :data="data"
      style="width: 100%;"
      :size="size"
    >
      <template v-for="item in columns" :key="item.prop">
        <el-table-column
          v-bind="item"
          :width="getColumnWidth(item)"
        >
          <template #default="{row, column}">
            <slot :name="item.prop" :row="row" :column="column">
              <el-image
                v-if="item.type === 'img'"
                :style="item.style || ''"
                :src="format({ row, item }, item.format)"
                :preview-src-list="item.preview ? [format({ row, item }, item.format)] : []"
                v-bind="item.imgProps"
              />
              <div v-else :style="item.style">{{ format({ row, item }, item.format) }}</div>
            </slot>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <div class="page-wrapper">
      <paging
        v-if="showPage && pageParams.total > pageParams.size"
        :pager="pageParams"
        @updatePager="updatePager"
      />
    </div>
  </div>
</template>

<script>
import paging from '@/components/pagination/index.vue';
import { defineComponent } from 'vue';

export default defineComponent({
  components: { paging },
  name: 'BasicTable',
  props: {
    columns: {
      type: Array,
      default: () => ([]),
    },
    data: {
      type: Array,
      default: () => ([]),
    },
    size: {
      type: String,
      default: 'small',
    },
    pageParams: {
      type: Object,
      default: () => ({
        current: Number,
        size: Number,
        total: Number,
        layout: String,
      }),
    },
    showPage: {
      type: Boolean,
      default: true,
    },
    tableLoading: Boolean,
  },
  emits: ['handleSearch', 'update:pageParams'],
  methods: {
    format({ row, item }, cb) {
      if (cb) return cb({ row, item });
      return row[item.prop];
    },
    getColumnWidth(item) {
      if (typeof item.width === 'string') return item.width;
      if (typeof item.width === 'number') return String(item.width);
      return 'auto';
    },
    handleSearch() {
      this.$emit('handleSearch');
    },
    updatePager(pager) {
      this.$emit('update:pageParams', pager);
      this.handleSearch();
    },
  },
});
</script>

<style lang="less" scoped>
.table-wrapper {
  .page-wrapper {
    padding: 12px 0;
    text-align: right;
  }
}
</style>
